package org.example.wratablecomparable;

import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * @ClassName FlowBean
 * @Author 小坏
 * @Date 2021/7/16、16:54
 * @Version 1.0
 * <p>
 * Hadoop 序列化 步骤
 * 1、定义类实现 Writable 接口
 * 2、重写序列化和反序列方法
 * 3、重写空参构造
 * 4、toString
 */

//TODO 1
public class FlowBean implements WritableComparable<FlowBean> {

    private long upFlow; //上行流量
    private long downFlow; //下行流量
    private long sumFlow; //总流量


    //TODO 3
    public FlowBean() {
    }

    // 序列化
    @Override
    public void write(DataOutput out) throws IOException {
        out.writeLong(upFlow);
        out.writeLong(downFlow);
        out.writeLong(sumFlow);
    }

    //反序列化
    @Override
    public void readFields(DataInput in) throws IOException {
        this.upFlow = in.readLong();
        this.downFlow = in.readLong();
        this.sumFlow = in.readLong();
    }


    public long getUpFlow() {
        return upFlow;
    }

    public void setUpFlow(long upFlow) {
        this.upFlow = upFlow;
    }

    public long getDownFlow() {
        return downFlow;
    }

    public void setDownFlow(long downFlow) {
        this.downFlow = downFlow;
    }

    public long getSumFlow() {
        return sumFlow;
    }

    public void setSumFlow(long sumFlow) {
        this.sumFlow = sumFlow;
    }

    //总流量
    public void setSumFlow() {
        this.sumFlow = this.downFlow + this.upFlow;
    }

    //改造ToString的输出
    @Override
    public String toString() {
        return upFlow + "\t" + downFlow + "\t" + sumFlow;
    }

    @Override
    public int compareTo(FlowBean o) {
        //按照总流量比较,倒序排列
        if (this.sumFlow > o.sumFlow) {
            return -1;
        } else if (this.sumFlow < o.sumFlow) {
            return 1;
        } else {
            //按照上行流量的正序排
            if (this.upFlow > o.upFlow) {
                return -1;
            } else if (this.upFlow < o.upFlow) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    /**
     *   输出格式：
     *
     *    1116            954           2070
     *   上行流量        下行流量       总流量
     */
}
